<?php
/**
 * @link         http://www.openzc.cn/
 * @author       hexipeng | e-mail:2017412656@qq.com
 * @copyright    Copyright (c) 2020, DesDev, Inc.
 * @license      http://www.openzc.cn/license.txt
 */
class product {
    
	/*获取商品列表*/
	function get_product_list($GET,$parameter){
		if($parameter['flag'] && $parameter['page']!=true){
			$sql=$this->get_flag_products($GET,$parameter);
		}else{
			$sql=$this->get_filter_search($GET,$parameter);
		}

		return $this->show_products_list($GET,$sql,$parameter);
	}
	
	//调用标签商品列表：特价，推荐，最新，促销
	function get_flag_products($GET,$parameter){
		global $predata_class;
		$orderby=$parameter['orderby'][1]." ".$parameter['orderby'][2];				
		$limit=$parameter['row'];
		$field="pd.products_name,p.*";
		if($parameter['desclen']){
			$field.=",left(pd.products_description,".$parameter['desclen'].") as products_description";
		}else{
			$field.=",pd.products_description";
		}
		if($parameter['pid']){
			$pid=str_replace(",","','",$parameter['pid']);
			$sql="select ".$field." from ".TABLE_PRODUCTS." p left join ".TABLE_PRODUCTS_DESCRIPTION." pd on p.products_id=pd.products_id where p.products_id in('".$pid."') and pd.language_id=".(int)$_SESSION['languages_id'];
			return $sql;
		}
	
		$categories=$predata_class->getPredata(TABLE_CATEGORIES);
		if($parameter['flag']=="true"){$parameter['flag']="";}
		
		switch ($parameter['flag']){
			case 'sale'://促销商品列表
				if($parameter['saleid']){
					$parameter['saleid']=join("','",array_unique(array_filter(explode(",",$parameter['saleid']))));
					$sql="select sale_categories_all from ".TABLE_SALEMAKER_SALES." where sale_status='1' and sale_id in('".$parameter['saleid']."')";
				}else{
					$sql="select sale_categories_all from ".TABLE_SALEMAKER_SALES." where sale_status='1'";
				}
				
				$sale=openzcQuery($sql);
				$sale=openzc_table_to_list($sale);
				
				if(count($sale)>0){
					foreach($sale as $k => $v){$cids.=$v['sale_categories_all'];}
				}
			
				if($cids){
					$cids=join(",",array_unique(array_filter(explode(",",$cids))));
					
					if($parameter['cid']!="all" && $parameter['cid'] ){
						$cids=openzc_get_intersect_ids($parameter['cid'],$cids);
						
					}
					$cids=join("','",array_unique(array_filter(explode(",",$cids))));
					
					$cid_where=" where master_categories_id in('".$cids."')";
				}else{
					$cid_where=" where master_categories_id=null";
				}
				$table="(select * from ".TABLE_PRODUCTS.$cid_where." limit ".$limit.") p left join ".TABLE_PRODUCTS_DESCRIPTION." pd on pd.products_id=p.products_id";
				$sql="select ".$field." from ".$table." where pd.language_id=".(int)$_SESSION['languages_id']." order by p.".$orderby;
			break;
			case 'featured'://推荐商品列表
				$table.=",".TABLE_FEATURED." f";
				if($parameter['cid']!="all" && $parameter['cid']){
					$cid=openzc_get_son_ids($categories,$parameter['cid']);
					$cid=join("','",array_unique(array_filter(explode(",",$cid))));
					$cid_where=" and p.master_categories_id in('".$cid."')";
				}
				$sql="select ".$field." from ".TABLE_FEATURED." f left join ".TABLE_PRODUCTS." p on p.products_id=f.products_id,".TABLE_PRODUCTS_DESCRIPTION." pd where p.products_id=pd.products_id and pd.language_id=".(int)$_SESSION['languages_id'].$cid_where." and f.status=1 order by p.".$orderby." limit ".$limit;
				
			break;
			case 'specials'://特价商品列表
				if($parameter['cid']!="all" && $parameter['cid']){
					$cid=openzc_get_son_ids($categories,$parameter['cid']);
					$cid=join("','",array_unique(array_filter(explode(",",$cid))));
					$cid_where=" and p.master_categories_id in('".$cid."')";
				}
				$field.=",s.*";
				$sql="select ".$field." from ".TABLE_SPECIALS." s left join ".TABLE_PRODUCTS." p on p.products_id=s.products_id,".TABLE_PRODUCTS_DESCRIPTION." pd where p.products_id=pd.products_id and pd.language_id=".(int)$_SESSION['languages_id'].$cid_where." and s.status=1 order by p.".$orderby." limit ".$limit;
			break;
			case 'bestsell':
				if($parameter['cid']!="all" && $parameter['cid']){
					$cid=openzc_get_son_ids($categories,$parameter['cid']);
					$cid=join("','",array_unique(array_filter(explode(",",$cid))));
					$cid_where=" and p.master_categories_id in('".$cid."')";
				}
				
				$sql="select ".$field." from ".TABLE_PRODUCTS." p left join ".TABLE_PRODUCTS_DESCRIPTION." pd on p.products_id = pd.products_id left join (select sum(products_quantity) as products_orders_count,products_id from ".TABLE_ORDERS_PRODUCTS." group by products_id) op on op.products_id=p.products_id where p.products_id=pd.products_id and pd.language_id=".(int)$_SESSION['languages_id'].$cid_where." order by op.products_orders_count desc limit ".$limit;
			break;
			case "rating":
				if($parameter['cid']!="all" && $parameter['cid']){
					$cid=openzc_get_son_ids($categories,$parameter['cid']);
					$cid=join("','",array_unique(array_filter(explode(",",$cid))));
					$cid_where=" and p.master_categories_id in('".$cid."')";
				}
				$sql="select ".$field." from ".TABLE_PRODUCTS." p left join ".TABLE_PRODUCTS_DESCRIPTION." pd on p.products_id = pd.products_id left join (select avg(reviews_rating) as products_rating,products_id from ".TABLE_REVIEWS." group by products_id) r on r.products_id=p.products_id where p.products_id=pd.products_id and pd.language_id=".(int)$_SESSION['languages_id'].$cid_where." order by r.products_rating desc limit ".$limit;
			break;
			case 'new':
				
				$cid_where=" where master_categories_id in('".$parameter['cid']."') ";
				$table="(select * from ".TABLE_PRODUCTS.$cid_where." order by ".$orderby." limit ".$limit.") p left join ".TABLE_PRODUCTS_DESCRIPTION." pd on pd.products_id=p.products_id";
				$sql="select ".$field." from ".$table." where pd.language_id=".(int)$_SESSION['languages_id']." order by p.".$orderby;
				
			break;
			default:
				if($parameter['cid']!="all" && $parameter['cid']){
					$cid_where=" where master_categories_id in('".$parameter['cid']."') ";
				}
				$table="(select * from ".TABLE_PRODUCTS.$cid_where.") p left join ".TABLE_PRODUCTS_DESCRIPTION." pd on pd.products_id=p.products_id";
				$sql="select ".$field." from ".$table." where pd.language_id=".(int)$_SESSION['languages_id']." order by p.".$orderby." limit ".$limit;
			break;
		}
		if(!$sql){
			$table="(select * from ".TABLE_PRODUCTS." limit ".$limit.") p left join ".TABLE_PRODUCTS_DESCRIPTION." pd on pd.products_id=p.products_id";
			$sql="select ".$field." from ".$table." where pd.language_id=".(int)$_SESSION['languages_id']." order by p.".$orderby;
		}
		return $sql;
	}
	//调用多条件商品列表：按品牌、属性、价格
	function get_filter_search($GET,$parameter){
		global $predata_class;
		$categories=$predata_class->getPredata(TABLE_CATEGORIES);

		$limit=$parameter['row'];
		$field="pd.products_name,pd.products_description,p.*";
		if($parameter['desclen']){
			$field.=",left(pd.products_description,".$parameter['desclen'].") as products_description";
		}
		$table="";
		//$where="p.products_id=pd.products_id and pd.language_id=".(int)$_SESSION['languages_id'];
		$where="";
		$between="";
		$filter=array();
		//按商品价格/属性/品牌查询
		if($GET['price']){$filter['price']=explode("|",$GET['price']);}
		if($GET['brand']){$filter['brand']=$GET['brand'];}
		if($GET['options'] || $GET['options']=='0'){$filter['attr']=$GET['options'];}
		if(count($filter)>0){
			foreach($filter as $k => $v){
				switch($k){
					case 'price':
						foreach($v as $a => $b){
							$b=explode(",",$b);
							if($where_price){$where_price .=" or ";}
							$where_price.="(products_price_sorter >= '".$b[0]."' and products_price_sorter < '".$b[1]."')";
							
							if($parameter['flag']=="specials"){
								$where_price_flag=" and (flag.specials_new_products_price >= '".$b[0]."' and flag.specials_new_products_price < '".$b[1]."')";
							}else{
								$where_price_flag=" and (p.products_price_sorter >= '".$b[0]."' and p.products_price_sorter < '".$b[1]."')";
							}
								
							
						
						}
						//$where.=" and ".$where_price;
						
						$between=" IF(s.status,s.specials_new_products_price >= '".$b[0]."' and s.specials_new_products_price < '".$b[1]."',p.products_price_sorter >= '".$b[0]."' and p.products_price_sorter < '".$b[1]."') and";
						if($parameter['flag']=="featured"){
							$where_price_flag=" and if(s.status=1,s.specials_new_products_price >= '".$b[0]."' and s.specials_new_products_price < '".$b[1]."',p.products_price_sorter >= '".$b[0]."' and p.products_price_sorter < '".$b[1]."')";
						}
					
					break;
					case 'brand':
						$v=str_replace(",","','",$v);
						$where.=" and p.manufacturers_id in('".$v."')";
						if($parameter['flag']=="specials" || $parameter['flag']=="featured" || $parameter['flag']=="search"){
							$where_brand_flag.=" and p.manufacturers_id in('".$v."')";
						}
					break;
					case 'attr':
						$v=explode(",",$v);
						$vtp=$predata_class->getPredata(TABLE_PRODUCTS_OPTIONS_VALUES_TO_PRODUCTS_OPTIONS);
						foreach($v as $a => $b){
							$options[$vtp[$b]['products_options_id']]['values'][]=$b;
						}
						foreach($options as $a => $b){ 
							$b="'".join("','",$b['values'])."'";
							$sql.=" and p.products_id in ( select products_id from ".TABLE_PRODUCTS_ATTRIBUTES." where options_values_id in(".$b."))";
							$where_attr_flag.=" and p.products_id in ( select products_id from ".TABLE_PRODUCTS_ATTRIBUTES." where options_values_id in(".$b."))";
							if($parameter['flag']=="specials" || $parameter['flag']=="featured" || $parameter['flag']=="search"){
								$where_attr_flag.=" and p.products_id in ( select products_id from ".TABLE_PRODUCTS_ATTRIBUTES." where options_values_id in(".$b."))";
							}
						}
						//$table=TABLE_PRODUCTS_ATTRIBUTES." pa,";
						$where.=" ".$sql;
					break;
				}
			}
		}
		
		if($parameter['cid']!="all" && $parameter['cid']){
			$cid=str_replace(",","','",$parameter['cid']);
			$where.=" and pt.categories_id in('".$cid."')";
		}
		if($parameter['page']==true && isset($_GET["page"])){
			$limit=($parameter['row']*($_GET['page']-1)).",".$parameter['row'];
		}
		
		$orderby=$parameter['orderby'];
		
		if($parameter['flag']){
			switch($parameter['flag']){
				case "specials": 
					$table = TABLE_SPECIALS." flag";
					if(explode(",",$_GET['orderby'])[0]=="price"){
						$orderby[0]="flag";
						$orderby[1]="specials_new_products_price";
					}
				break;
				case "featured": 
					$table = TABLE_FEATURED." flag left join ".TABLE_SPECIALS." s on s.products_id=flag.products_id";
				break;
				
			}
			if($parameter['flag']=="search"){
				$table.= TABLE_PRODUCTS." p left join ".TABLE_PRODUCTS_DESCRIPTION." pd on pd.products_id=p.products_id";
			}else{
				$table.=" left join ".TABLE_PRODUCTS." p on p.products_id=flag.products_id left join ".TABLE_PRODUCTS_DESCRIPTION." pd on pd.products_id = flag.products_id";
			}

			if($where_attr_flag){
				if($parameter['flag']=="search"){
					$table.=" left join ".TABLE_PRODUCTS_ATTRIBUTES." pa on p.products_id=pa.products_id";
				}else{
					$table.=" left join ".TABLE_PRODUCTS_ATTRIBUTES." pa on flag.products_id=pa.products_id";
				}
				
			}
			if($orderby[3]==TABLE_ORDERS_PRODUCTS){
				$table.=" left join (select sum(products_quantity) as products_orders_count,products_id from ".TABLE_ORDERS_PRODUCTS." group by products_id) op on p.products_id=op.products_id";
			}
			$where=$where_price_flag.$where_brand_flag.$where_attr_flag;
			
			if($parameter['flag']=="search"){
				if(isset($_GET['keyword'])){
					$where.=" and pd.products_name like '%".$_GET['keyword']."%'";
					if(isset($_GET['categories_id'])){
						$where.=" and p.master_categories_id in('".$_GET['categories_id']."')";
					}
				}
			}
			
			$GLOBALS['page_sql']=$where;
			if($parameter['flag']=="search"){
				$sql="select p.*,pd.products_name from ".$table." where pd.language_id=".(int)$_SESSION['languages_id']." ".$where." group by p.products_id order by ".$orderby[0].".".$orderby[1]." ".$orderby[2]." limit ".$limit;
			}else{
				$sql="select p.*,pd.products_name from ".$table." where flag.status='1' and pd.language_id=".(int)$_SESSION['languages_id']." ".$where." group by p.products_id order by ".$orderby[0].".".$orderby[1]." ".$orderby[2]." limit ".$limit;
			}
		}else{
			$GLOBALS['page_sql']=$where.$where_price_flag.$where_brand_flag.$where_attr_flag;
			$specials="left join ".TABLE_SPECIALS." s on s.products_id=p.products_id";
			switch($orderby[3]){
				case TABLE_ORDERS_PRODUCTS:
					$table.=TABLE_PRODUCTS_TO_CATEGORIES." pt on pt.products_id=p.products_id ".$specials." left join ".TABLE_PRODUCTS_DESCRIPTION." pd on pd.products_id=p.products_id left join (select sum(products_quantity) as products_orders_count,products_id from ".TABLE_ORDERS_PRODUCTS." group by products_id) op on op.products_id=p.products_id";
				break;
				default:
					$table.=TABLE_PRODUCTS_TO_CATEGORIES." pt on pt.products_id=p.products_id ".$specials." left join ".TABLE_PRODUCTS_DESCRIPTION." pd on pd.products_id=p.products_id";
				break;
			}
			$sql="select ".$field." from ".TABLE_PRODUCTS." p left join ".$table." where".$between." pd.language_id='".(int)$_SESSION['languages_id']."'".$where." order by ".$orderby[0].".".$orderby[1]." ".$orderby[2]." limit ".$limit;
		}
		return $sql;
	}
	
	//商品列表展示
	function show_products_list($GET,$sql,$parameter=[]){
		global $predata_class;

		$data=openzcQuery($sql);
		if($parameter['index_field']){
			$data=openzc_table_to_list($data,$parameter['index_field']);
		}else{
			$data=openzc_table_to_list($data);
		}

		$allpid=$this->getAllpid($data);
		$categories=$predata_class->getPredata(TABLE_CATEGORIES);
	    $products_rating=$this->get_products_reviews_rating($data);
	    $currencies_symbol_left=$predata_class->getPredata(TABLE_CURRENCIES);
		$featured=openzcQuery("select * from ".TABLE_FEATURED." where products_id in(".$allpid.") and status='1'");
		$featured=openzc_table_to_list($featured,"products_id");
		foreach($data as $k => $v){
			$v["sort_index"]=$k+1;
			if(isset($parameter['type']) && $parameter['type']=="compare"){
				$v['products_compare']=true;
			}
			$v['allpid']=$allpid;
			$v["products_price"]="";
			$v['products_price_string']=zen_get_products_display_price($v['products_id']);
			$v['categories_name']=$categories[$v['master_categories_id']]['categories_name'];
			$v['categories_link']=$categories[$v['master_categories_id']]['categories_link'];
			$this->get_display_price($v);
			
			foreach($GLOBALS['products_price_array'][$v['products_id']] as $a => $b){
				$v[$a]=$b;
				if($a=="normalprice" || $a=="productBasePrice"){
					$v['products_original_price']=$b;
				}else if($a=="productSpecialPrice" || $a=="productSpecialPriceSale" || $a=="productSalePrice"){
					$v['products_price']=$b;
				}
				if($a=="productSalePrice"){
					$v['products_flag'].=",sale";
					$sale = openzcQuery("select * from " . TABLE_SALEMAKER_SALES . " where sale_categories_all like '%," . $v['master_categories_id'] . ",%' and sale_status = '1' and (sale_date_start <= now() or sale_date_start = '0001-01-01') and (sale_date_end >= now() or sale_date_end = '0001-01-01') and (sale_pricerange_from <= '" . $GLOBALS['products_price_array'][$v['products_id']]['products_normal_price'] . "' or sale_pricerange_from = '0') and (sale_pricerange_to >= '" . $GLOBALS['products_price_array'][$v['products_id']]['products_normal_price'] . "' or sale_pricerange_to = '0')");
					$v['sale_date_end']=$sale->fields['sale_date_end'];
				}
				if($a=="productSpecialPrice"){$v['products_flag'].=",special";}
			}
			
			if(isset($featured[$v['products_id']])){$v['products_flag'].=",featured";}
			if(isset($v["expires_date"])){
				$expires_date=strtotime($v['expires_date']);
				$v['expires_date_secound']=$expires_date*1000;
			}
			if(!$v['products_price']){
				$v['products_price']=$v['products_original_price'];
			}
			$v['products_price_number']=str_replace($currencies_symbol_left[$_SESSION['currency']]['symbol_left'],"",$v['products_price']);
			//**products_image
			$flip_image=explode("|||",$v['products_image_detail'])[0];
			
			$v['products_image_full']=$this->get_products_image($v['products_image']);
			$v['products_image']=$this->get_products_image($v['products_image'],$parameter['imgsizer'],$parameter['bgcolor']);
			
			if(!$flip_image){
				$v['products_image_flip_full']=$this->get_products_image($v['products_image']);
			}else{
				$v['products_image_flip_full']=$this->get_products_image($flip_image);
			}
			$v['products_image_flip']=$this->get_products_image($v['products_image_flip_full'],$parameter['imgsizer'],$parameter['bgcolor']);
			
			$cPath=$categories[$v['master_categories_id']]['path'];
			$v['products_link']=zen_href_link(FILENAME_PRODUCT_INFO,'cPath='.$cPath.'&products_id='.$v['products_id']);
			$v['products_rating']=$products_rating[$v["products_id"]];
			if(isset($v['products_description'])){
				$v['products_description']=strip_tags($v['products_description']);
			}
			$datalist[$k]=$v;
		}

		if($parameter['page']==true){
			if($parameter['flag']){
				switch($parameter['flag']){
					case "specials":
						$table=TABLE_SPECIALS." flag";
					break;
					case "featured":
						$table=TABLE_FEATURED." flag left join ".TABLE_SPECIALS." s on s.products_id=flag.products_id";
					break;
				}
				if($parameter['flag']=="search"){
					$table.= TABLE_PRODUCTS." p left join ".TABLE_PRODUCTS_DESCRIPTION." pd on p.products_id=pd.products_id";
				}else{
					$table.=" left join ".TABLE_PRODUCTS." p on flag.products_id=p.products_id";
				}
				
				if(isset($_GET['options'])){
					$table.=" left join ".TABLE_PRODUCTS_ATTRIBUTES." pa on p.products_id=pa.products_id";
				}
				if($parameter['flag']=="search"){
					$sql="select count(distinct p.products_id) as total from ".$table." where pd.language_id=".(int)$_SESSION['languages_id'].$GLOBALS['page_sql'];
				}else{
					$sql="select count(distinct flag.products_id) as total from ".$table." where flag.status='1' ".$GLOBALS['page_sql'];
				}
				
			}else{
				$sql="select count(distinct p.products_id) as total from ".TABLE_PRODUCTS_TO_CATEGORIES." pt,".TABLE_PRODUCTS." p where p.products_id=pt.products_id".$GLOBALS['page_sql'];
			}
		
			//echo "<br/>".$sql;
			$total=openzcQuery($sql);
			//echo $total->fields['total'];exit;
			$list['total']=$total->fields['total'];
			
			$list['datalist']=$datalist;
			$datalist=$list;
		}
	
		return $datalist;
	}
	private function getAllpid($products){
		foreach($products as $k => $v){$pids[]=$v['products_id'];}
		$pids="'".join("','",$pids)."'";
		return $pids;
	}
	
	private function get_display_price($data){
		global $currencies;
		if(isset($GLOBALS['products_price_array'][$products_id])){return false;}
		$products_id=$data['products_id'];
		$display_normal_price = zen_get_products_base_price($products_id);
		$GLOBALS['products_price_array'][$products_id]['products_normal_price']=$display_normal_price;
		$display_special_price = zen_get_products_special_price($products_id, true);
		$display_sale_price = zen_get_products_special_price($products_id, false);
	
		if (SHOW_SALE_DISCOUNT_STATUS == '1' and ($display_special_price != 0 or $display_sale_price != 0)) {
			if ($display_sale_price) {
				if (SHOW_SALE_DISCOUNT == 1) {
					if ($display_normal_price != 0) {
						$show_discount_amount = number_format(100 - (($display_sale_price / $display_normal_price) * 100),SHOW_SALE_DISCOUNT_DECIMALS);
					} else {
						$show_discount_amount = '';
					}
					$string=PRODUCT_PRICE_DISCOUNT_PREFIX . $show_discount_amount . PRODUCT_PRICE_DISCOUNT_PERCENTAGE;
					$GLOBALS['products_price_array'][$products_id]['productPriceDiscount']=$string;
				}else{
					$string=PRODUCT_PRICE_DISCOUNT_PREFIX . $currencies->display_price(($display_normal_price - $display_sale_price), zen_get_tax_rate($product_check->fields['products_tax_class_id'])) . PRODUCT_PRICE_DISCOUNT_AMOUNT;
					$GLOBALS['products_price_array'][$products_id]['productPriceDiscount']=$string;
				}
			} else {
				if (SHOW_SALE_DISCOUNT == 1) {
					$string=PRODUCT_PRICE_DISCOUNT_PREFIX . number_format(100 - (($display_special_price / $display_normal_price) * 100),SHOW_SALE_DISCOUNT_DECIMALS) . PRODUCT_PRICE_DISCOUNT_PERCENTAGE;
					$GLOBALS['products_price_array'][$products_id]['productPriceDiscount']=$string;
				} else {
					$string=PRODUCT_PRICE_DISCOUNT_PREFIX . $currencies->display_price(($display_normal_price - $display_special_price), zen_get_tax_rate($product_check->fields['products_tax_class_id'])) . PRODUCT_PRICE_DISCOUNT_AMOUNT;
					$GLOBALS['products_price_array'][$products_id]['productPriceDiscount']=$string;
				}
			}
		}
		if ($display_special_price) {
			$string=$currencies->display_price($display_normal_price, zen_get_tax_rate($product_check->fields['products_tax_class_id']));
			$GLOBALS['products_price_array'][$products_id]['normalprice']=$string;
			if ($display_sale_price && $display_sale_price != $display_special_price) {
				$string=$currencies->display_price($display_special_price, zen_get_tax_rate($product_check->fields['products_tax_class_id']));
				$GLOBALS['products_price_array'][$products_id]['productSpecialPriceSale']=$string;
				if ($product_check->fields['product_is_free'] == '1') {
					$string=PRODUCT_PRICE_SALE . '<s>' . $currencies->display_price($display_sale_price, zen_get_tax_rate($product_check->fields['products_tax_class_id'])) . '</s>';
					$GLOBALS['products_price_array'][$products_id]['productSalePrice']=$string;
				} else {
					$string=PRODUCT_PRICE_SALE . $currencies->display_price($display_sale_price, zen_get_tax_rate($product_check->fields['products_tax_class_id']));
					$GLOBALS['products_price_array'][$products_id]['productSalePrice']=$string;
				}
			} else {
				if ($product_check->fields['product_is_free'] == '1') {
					$string='<s>' . $currencies->display_price($display_special_price, zen_get_tax_rate($product_check->fields['products_tax_class_id'])) . '</s>';
					$GLOBALS['products_price_array'][$products_id]['productSpecialPrice']=$string;
				} else {
					$string=$currencies->display_price($display_special_price, zen_get_tax_rate($product_check->fields['products_tax_class_id']));
					$GLOBALS['products_price_array'][$products_id]['productSpecialPrice']=$string;
				}
				$show_sale_price = '';
			}
		} else {
			if ($display_sale_price) {
				$string=$currencies->display_price($display_normal_price, zen_get_tax_rate($product_check->fields['products_tax_class_id']));
				$GLOBALS['products_price_array'][$products_id]['normalprice']=$string;
				$show_special_price = '';
				$string=PRODUCT_PRICE_SALE . $currencies->display_price($display_sale_price, zen_get_tax_rate($product_check->fields['products_tax_class_id']));
				$GLOBALS['products_price_array'][$products_id]['productSalePrice']=$string;
			} else {
				if ($product_check->fields['product_is_free'] == '1') {
					$string='<s>' . $currencies->display_price($display_normal_price, zen_get_tax_rate($product_check->fields['products_tax_class_id'])) . '</s>';
					$GLOBALS['products_price_array'][$products_id]['productFreePrice']=$string;
				} else {
					$string=$currencies->display_price($display_normal_price, zen_get_tax_rate($product_check->fields['products_tax_class_id']));
					$GLOBALS['products_price_array'][$products_id]['productBasePrice']=$string;
				}
			}
		}
		
	}
	
	public function get_products_reviews_rating($data){
		foreach($data as $k => $v){
			$pids[]=$v['products_id'];
		}
		$pids="'".join("','",$pids)."'";
		$sql="select count(reviews_id) as count,sum(reviews_rating) as sum,products_id from ".TABLE_REVIEWS." where status='1' and products_id in(".$pids.") group by products_id";
		$data=openzcQuery($sql);
		$data=openzc_table_to_list($data,"products_id");
		foreach($data as $k => $v){
			$result[$k]=number_format($v['sum']/$v['count'],1);
		}
		return $result;
	}
	//获取主图
	function get_products_image($images='',$sizer='',$bgcolor=''){
		global $ImageSizer;
		if(!is_dir(IMGCACHE_DIR)){mkdir(IMGCACHE_DIR);}
		$images=explode("|||",$images);
		if(is_file("./images/".$images[0])){
			$result="/images/".$images[0];
		}else if(is_file("./".$images[0])){
			$result="/".$images[0];
		}
		if($sizer){
			$sizer=explode(",",$sizer);
			$imgname=getCacheImgname(basename($result));
			$imgdir=IMGCACHE_DIR.$sizer[0]."-".$sizer[1]."/";
			$image_new=$imgdir.$imgname;
			if(!is_dir($imgdir)){
				mkdir($imgdir);
			}
			if(getCacheImgcheck($image_new)==true){
				$ImageSizer->Run(".".$result);
				$ImageSizer->resize($sizer[0],$sizer[1],$bgcolor);
				$ImageSizer->save($image_new);
			}
			$result="/".str_replace(ROOT_PATH,"",$imgdir).$imgname;
		}
		return $result;
	}
	//商品列表分页
	function get_products_list_page($GET,$parameter){
		
		if(array_key_exists("limit",$GET)){
			$pernum=$GET['limit'];
		}else{
			$pernum=$parameter['pernum'];
		}
		
		$total=$parameter['total'];
		
		$rows=ceil($total / $pernum);//获取页数
        if(!array_key_exists("page",$GET)){$GET['page']=1;}
		if($parameter['listitem']){
			foreach($GET as $k => $v){
				if($k!="main_page" && $k!="page" && $k != "sort"){$str.=$k."=".$v."&";}
			}
			
			$str.="#";
			$str=str_replace("&#","",$str);
			$str=str_replace("#","",$str);
			if(isset($parameter['listsize'])){
				$listsize=$parameter["listsize"];
				if($listsize<5) $listsize=5;
			}else{
				$listsize="5";
			}
			if($listsize%2==0){
				$n1=($listsize/2)-1;
				$n2=$listsize/2;
			}else{
				$n1=$n2=($listsize-1)/2;
			}
			
			$a=$GET['page']-$n1;
			if($a<=0){$n2=$n2+abs($a)+$GET['page']+1;$n1=1;}
			else{$n1=$GET['page']-$n1;$n2=$n2+$GET['page']+1;}
		    if($rows<=$listsize){
				$n1=1;$n2=$rows;
			}
			
			for($i=1;$i<=$rows;$i++){
				if( $n1 <= $i && $i <= $n2 ){
					$list['list'][$i]['text']=$i;
					$list['list'][$i]['link']=zen_href_link($GET['main_page'],$str."&page=".$i);
					if($i==$GET['page']){
						$list['list'][$i]['status']="active";
					}
				}
			}
			if($GET['page']==1){
				$list['next']['text']="Next";
				$list['next']['link']=$list['list'][$GET['page']+1]['link'];
			}
			else if($GET['page']>1 && $GET['page']<$rows){
				$list['prev']['text']="Previous";
				$list['prev']['link']=$list['list'][$GET['page']-1]['link'];
				$list['next']['text']="Next";
				$list['next']['link']=$list['list'][$GET['page']+1]['link'];
			}
			else if($GET['page']==$rows){
				$list['prev']['text']="Previou";
				$list['prev']['link']=$list['list'][$GET['page']-1]['link'];
			}
		
			$list['first']=array('text'=>'Home page','link'=>zen_href_link($GET['main_page'],$str."&page=1"));
			$list['last']=array('text'=>'Last page','link'=>zen_href_link($GET['main_page'],$str."&page=".$rows));
		
			if($GET['page']==1){unset($list['first']);unset($list['prev']);}
			if($GET['page']==$rows){unset($list['last']);unset($list['next']);}
			
		}
		if($parameter['info']){
			$list['info']['pageno']=$rows;
			$list['info']['total']=$total;
			$list['info']['pernum']=$pernum;
			if($total < $GET['page']*$pernum){
				$list['info']['range']=((($GET['page']-1)*$pernum)+1)."-".$total;
			}else{
				$list['info']['range']=((($GET['page']-1)*$pernum)+1)."-".$GET['page']*$pernum;
			}
		}
		return $list;
	}
	//获取商品详情
	function get_products_info($pid){
		
		$sql="select p.*,pd.* from ".TABLE_PRODUCTS." p,".TABLE_PRODUCTS_DESCRIPTION." pd where p.products_id=pd.products_id and p.products_id='".$pid."' and pd.language_id=".(int)$_SESSION['languages_id'];
		$products=$this->show_products_list($_GET,$sql)[0];
		
		//$products["products_image"]=$this->get_products_image($products["products_image"]);
		$reviews_count=openzcQuery("select count(reviews_id) as count from ".TABLE_REVIEWS." where products_id=".$pid." and status=1");
		$products["products_reviews_count"]=$reviews_count->fields['count'];
		return $products;
	}
	
	function get_products_detail_image($pid){
		$sql="select products_image,products_image_detail from ".TABLE_PRODUCTS." where products_id='".$pid."'";
		$products=openzcQuery($sql);
		$products=openzc_table_to_list($products)[0];
		$images=array_filter(explode("|||",$products["products_image_detail"]));
	
	    $images=$this->get_products_detail_dirimage($products["products_image"],$images);	
		
		array_unshift($images,$products["products_image"]);
		$images=array_filter($images);
		
		
		return $images;
	}
	function get_products_detail_dirimage($index_image,$detail=[]){
		
		if(!$index_image){return false;}
		else{
			$info=explode("/",$index_image);
			$size=count($info);
			
			$images=explode(".",$info[($size-1)]);
			unset($info[($size-1)]);
			foreach($info as $k => $v){
				@$path.=$v."/";
			}
			$images_name=$images[0];
			$images_suffix=$images[1];
			for($i=1;$i<10;$i++){
				$img=$path.$images_name."_0".$i.".".$images_suffix;
				
				if(is_file("./images/".$img)){$detail[]=$img;}
				$imgs=$path.$images_name."-0".$i.".".$images_suffix;
				if(is_file("./images/".$imgs)){$detail[]=$imgs;}
			}
			$detail=array_unique($detail);
		
			return $detail;
		}
	}
	function get_pagelist_total(){
		global $predata_class;
		switch($_GET['main_page']){
			case "index":
				$cid=openzc_get_current_cpath($_GET['cPath']);
				$categories=$predata_class->getPredata(TABLE_CATEGORIES);
				$cid=str_replace(",","','",openzc_get_son_ids($categories,$cid,$cid));
				$parameter=array('cid'=>$cid,"table"=>TABLE_PRODUCTS,"as"=>"p","status"=>"products_status");
			break;
			case "specials":
				$parameter=array('cid'=>"all","table"=>TABLE_SPECIALS,"as"=>"s","status"=>"status");
			break;
			case "featured_products":
				$parameter=array('cid'=>"all","table"=>TABLE_FEATURED,"as"=>"f","status"=>"status");
			break;
			default:
				$parameter=array('cid'=>"all","table"=>TABLE_PRODUCTS,"as"=>"p","status"=>"products_status");
			break;
		}
		$sql=$this->get_pagelist_sql($_GET,$parameter);
		
		$count=openzcQuery($sql);
		return $count->fields['count'];
	}
	function get_pagelist_sql($GET,$parameter){
		global $predata_class;
		$as=$parameter['as'];
		$table=$parameter["table"]." ".$as;
		$where=" ".$as.".".$parameter["status"]."=1";
		if($parameter['cid']!=="all"){
			$where.=" and p.master_categories_id in('".$parameter['cid']."')";
		}
		if($parameter["table"]!=TABLE_PRODUCTS){
			$table.=" left join ".TABLE_PRODUCTS." p on p.products_id=".$as.".products_id";
		}
		foreach($GET as $k => $v){
			switch($k){
				case "brand":
					$v=array_filter(explode(",",$v));
					$brand=join("','",$v);
					$where.=" and p.manufacturers_id in('".$brand."')";
				break;
				case "price":
					$v=array_filter(explode("|",$v));
					$first=key($v);
					foreach($v as $a => $b){
						$b=explode(",",$b);
						if(count($v)>1){
							if($first==$a){
								if($_GET['main_page']=="specials"){
									$price.="(s.specials_new_products_price>='".$b[0]."' and s.specials_new_products_price < '".$b[1]."') ";
								}else{
									$price.="(p.products_price_sorter>='".$b[0]."' and p.products_price_sorter < '".$b[1]."') ";
								}
							}else{
								if($_GET['main_page']=="specials"){
									$price.=" or (s.specials_new_products_price>='".$b[0]."' and s.specials_new_products_price < '".$b[1]."')";
								}else{
									$price.=" or (p.products_price_sorter>='".$b[0]."' and p.products_price_sorter < '".$b[1]."')";
								}
							}
						}else{
							if($_GET['main_page']=="specials"){
								$price="s.specials_new_products_price>='".$b[0]."' and s.specials_new_products_price < '".$b[1]."'";
							}else{
								$price="p.products_price_sorter>='".$b[0]."' and p.products_price_sorter < '".$b[1]."'";
							}
						}
					}
					$where.=" and (".$price.")";
				break;
				case "options":
					$v=array_filter(explode(",",$v));
					$vtp=$predata_class->getPredata(TABLE_PRODUCTS_OPTIONS_VALUES_TO_PRODUCTS_OPTIONS);
					foreach($v as $a => $b){
						$options_data[$vtp[$b]["products_options_id"]][]=$b;
					}
					$table.=" left join ".TABLE_PRODUCTS_ATTRIBUTES." pa on pa.products_id=p.products_id";
					foreach($options_data as $a => $b){
						$vid="'".join("','",$b)."'";
						$options.=" and p.products_id in ( select products_id from ".TABLE_PRODUCTS_ATTRIBUTES." where options_values_id in(".$vid.") )";
					}
					$where.=$options;
				break;
				case "keyword":
					$table.=" left join ".TABLE_PRODUCTS_DESCRIPTION." pd on pd.products_id=p.products_id";
					$key=" and pd.products_name like '%".$v."%' and pd.language_id=".(int)$_SESSION['languages_id'];
					$where.=$key;
				break;
				case "categories_id":
					$cid=" and p.master_categories_id in('".$v."')";
				break;
			}
		}
		$sql="select count(distinct p.products_id) as count from ".$table." where ".$where;
		
		return $sql;
	}
	function get_pagelist_pernum(){
		if(array_key_exists("limit",$_GET)){
			$pernum=$_GET['limit'];
		}else{
			$file=TPLCACHE_TPL."tplCacheCount_".md5("tplCacheCount").".inc";
			$json=file_get_contents($file);
			$json=json_decode($json,true);
			$pernum=$json[$_GET['main_page']]['pagesize'];
		}
		return $pernum;
	}
	
}
?>